/**
 * TabList - Tab Container with Scroll and Drag Support
 * 
 * Features:
 * - Horizontal scroll
 * - Drag to reorder
 * - Add new tab button
 * - Overflow handling
 */

import React, { useRef, useState, type ReactNode } from 'react';
import { Plus, ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

export interface TabListProps {
  children: ReactNode;
  onAdd?: () => void;
  showAddButton?: boolean;
  className?: string;
  maxTabs?: number;
}

export function TabList({
  children,
  onAdd,
  showAddButton = true,
  className,
  maxTabs,
}: TabListProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [showLeftScroll, setShowLeftScroll] = useState(false);
  const [showRightScroll, setShowRightScroll] = useState(false);

  const checkScroll = () => {
    const el = scrollRef.current;
    if (!el) return;

    setShowLeftScroll(el.scrollLeft > 0);
    setShowRightScroll(
      el.scrollLeft < el.scrollWidth - el.clientWidth - 1
    );
  };

  const scroll = (direction: 'left' | 'right') => {
    const el = scrollRef.current;
    if (!el) return;

    const scrollAmount = 200;
    const targetScroll = direction === 'left'
      ? el.scrollLeft - scrollAmount
      : el.scrollLeft + scrollAmount;

    el.scrollTo({
      left: targetScroll,
      behavior: 'smooth',
    });

    setTimeout(checkScroll, 100);
  };

  return (
    <div className={cn('relative flex items-center bg-background', className)}>
      {/* Left Scroll Button */}
      {showLeftScroll && (
        <Button
          variant="ghost"
          size="icon"
          className="absolute left-0 z-10 h-8 w-8 rounded-full shadow-md bg-background/90"
          onClick={() => scroll('left')}
        >
          <ChevronLeft className="w-4 h-4" />
        </Button>
      )}

      {/* Tab Container */}
      <div
        ref={scrollRef}
        onScroll={checkScroll}
        className={cn(
          'flex-1 flex items-center gap-1',
          'overflow-x-auto overflow-y-hidden',
          'scrollbar-thin scrollbar-thumb-muted scrollbar-track-transparent',
          'px-2 py-1'
        )}
      >
        {children}
      </div>

      {/* Right Scroll Button */}
      {showRightScroll && (
        <Button
          variant="ghost"
          size="icon"
          className="absolute right-12 z-10 h-8 w-8 rounded-full shadow-md bg-background/90"
          onClick={() => scroll('right')}
        >
          <ChevronRight className="w-4 h-4" />
        </Button>
      )}

      {/* Add New Tab Button */}
      {showAddButton && onAdd && (
        <Button
          variant="ghost"
          size="icon"
          className="flex-shrink-0 h-8 w-8 mr-1"
          onClick={onAdd}
          disabled={maxTabs !== undefined && React.Children.count(children) >= maxTabs}
          title="新建 (Ctrl+T)"
        >
          <Plus className="w-4 h-4" />
        </Button>
      )}
    </div>
  );
}

